<script setup lang="ts">
import { Delete, Edit } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import {
  defaultFormData,
  defaultPagingParams,
} from '../index'
import { FormModal, SearchForm } from './index'
import { PAGING } from '@/constant'
import type { TableColumn } from '@/types'
// ------------------use------------------
// #region
const open = defineModel<boolean>('open', {
  default: false,
  required: true,
})
const { globalProperties } = useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<any[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [pagingParams, setPagingParams] = useState<any>({
  ...defaultPagingParams,
})
const [total, setTotal] = useState<number>(0)
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [isEdit, setIsEdit] = useState<boolean>(false)
const { $message } = useCurrentInstance()
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<any>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '名称',
    render() {
      return '名称'
    },
  },
  {
    key: uuid(),
    label: '所属部门、公司',
    render() {
      return '部门、公司'
    },
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef = ref<InstanceType<typeof FormModal>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
function back() {
  open.value = false
}
async function deleteData(id: number) {
  const res: Action = await globalProperties
    .$confirm(
      '该操作将永久删除该数据，确定删除？',
      '警告',
      {
        type: 'warning',
      },
    )
    .catch(e => e)

  if (res !== 'confirm')
    return
  globalProperties.$message.success(
    `${id ?? ''}删除成功！`,
  )
  getTableData()
}
async function showEditDialog(row: any) {
  setFormModalTitle('编辑')
  setIsEdit(true)
  setFormData({ ...defaultFormData, ...row })
  await nextTick()
  modalRef.value?.open()
}
async function showAddDialog() {
  setFormModalTitle('新增')
  setIsEdit(false)
  setFormData({ ...defaultFormData })
  await nextTick()
  modalRef.value?.open()
}
async function getTableData() {
  await withLoading(sleep)(1000)

  setTotal(30)
  setTableData(Array.from({ length: 30 }).fill({}))
}
async function addOrUpdateData(row: any) {
  await sleep(1000)
  getTableData()
  globalProperties.$message.success(
    `${row.id ?? ''}数据更新成功！`,
  )
}
function addData() {
  addOrUpdateData(formData.value)
  modalRef.value?.close()
  $message.success('保存成功！')
}
function editData() {
  addOrUpdateData(formData.value)
  modalRef.value?.close()
  $message.success('保存成功！')
}
/** 重置 */
function reset() {
  setPagingParams({ ...defaultPagingParams })
  getTableData()
}
function search() {
  getTableData()
  Object.assign(pagingParams.value, PAGING.PARAMS)
}
function handleSaveSuccess() {
  isEdit.value ? editData() : addData()
}
// #endregion
</script>

<template>
  <Transition
    leave-active-class="animate__animated animate__faster  animate__fadeOut"
    enter-active-class="animate__animated animate__faster  animate__fadeIn"
  >
    <div
      v-show="open"
      class="padding-sm flex-direction manage box-border flex gap-sm"
    >
      <div class="flex-incompressible manage__header">
        <el-page-header title="人员架构图" @back="back">
          <template #content>
            <span>数据管理</span>
          </template>
        </el-page-header>
      </div>
      <div
        class="flex-fillRemaining overflow flex-direction manage__body flex align-end"
      >
        <view-table
          :loading="loading"
          :columns="columns"
          :data="tableData"
        >
          <template #actions>
            <SearchForm
              @search="search"
              @reset="reset"
              @plus="showAddDialog"
            />
          </template>
          <template #operate="{ row }">
            <TdButton
              title="编辑"
              :icon="Edit"
              type="primary"
              @click="showEditDialog(row)"
            />
            <el-divider direction="vertical" />
            <TdButton
              title="删除"
              :icon="Delete"
              type="danger"
              @click="deleteData(row.id)"
            />
          </template>
        </view-table>

        <!-- 分页 -->
        <ListsPagination
          v-model:page-num="pagingParams.pageNumber"
          v-model:page-size="pagingParams.pageSize"
          :total="total"
          @current-change="getTableData"
          @size-change="getTableData"
        />
      </div>
      <FormModal
        ref="modalRef"
        :title="formModalTitle"
        :data="formData"
        @save-success="handleSaveSuccess"
      />
    </div>
  </Transition>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
